package lancs.mobilemedia.core.ui.controller;

import java.util.Vector;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.rms.RecordStoreFullException;

import lancs.mobilemedia.core.ui.MainUIMidlet;
import lancs.mobilemedia.core.ui.datamodel.AlbumData;
import lancs.mobilemedia.core.ui.screens.AlbumListScreen;
import lancs.mobilemedia.core.util.Constants;
import lancs.mobilemedia.factories.FavouritesSPLFactory;
import lancs.mobilemedia.factories.SortingSPLFactory;
import lancs.mobilemedia.lib.exceptions.PersistenceMechanismException;

public class AlbumController extends AbstractController {
	
	private ControllerCommand command;
	
	private ControllerMapper mapper;
	
	private Vector splFactories;
	
	public AlbumController(MainUIMidlet midlet, AlbumData albumData, AlbumListScreen albumListScreen) {
		super(midlet, albumData, albumListScreen);
		init();
	}

	public void init() {
		createFactories();
		createControllerMapper();
	}
	
	private void createFactories() {
		splFactories = new Vector();
		// if Sorting feature is enabled
		splFactories.addElement(new SortingSPLFactory());
		// if Favourites feature is enable
		splFactories.addElement(new FavouritesSPLFactory());
	}

	public void createControllerMapper() {
		mapper = (ControllerMapper) new AlbumControllerMapper();
	}
	
	public boolean handleCommand(Command c) {
		String label = c.getLabel();
		System.out.println("<* AlbumController.handleCommand() *>: " + label);

		command = (ControllerCommand) mapper.getCommand(label);

		if (command != null) {
			return command.execute(this);
		}
		return false;
	}

	public void resetImageData() {
		try {
			getAlbumData().resetImageData();
		} catch (PersistenceMechanismException e) {
			Alert alert = null;
			if (e.getCause() instanceof RecordStoreFullException)
				alert = new Alert("Error", "The mobile database is full", null, AlertType.ERROR);
			else
				alert = new Alert("Error", "It is not possible to reset the database", null, AlertType.ERROR);
			Display.getDisplay(midlet).setCurrent(alert, Display.getDisplay(midlet).getCurrent());
			return;
		}

		for (int i = 0; i < getAlbumListScreen().size(); i++) {
			getAlbumListScreen().delete(i);
		}

		String[] albumNames = getAlbumData().getAlbumNames();
		for (int i = 0; i < albumNames.length; i++) {
			if (albumNames[i] != null) {
				getAlbumListScreen().append(albumNames[i], null);
			}
		}
		setCurrentScreen(getAlbumListScreen());
	}

	public boolean goToPreviousScreen() {
		System.out.println("<* AlbumController.goToPreviousScreen() *>");
		getAlbumListScreen().repaintListAlbum(getAlbumData().getAlbumNames());
		setCurrentScreen(getAlbumListScreen());
		ScreenSingleton.getInstance().setCurrentScreenName(Constants.ALBUMLIST_SCREEN);
		return false;
	}
}